using System;
using System.Text;
using XcoAppSpaces.Transport.Sockets.Auth.Contract;
using XcoAppSpaces.Transport.Sockets.Auth.Contract.DoServerHandshake;

namespace XcoAppSpaces.Transport.Sockets.Auth
{
	class ReceiveGreeting : IReceiveGreeting
	{
		private byte[] greetingBytes;
		//private int maxWaitForGreetingSeconds;

		public void In_Connection(ConnectionInfo conn)
		{
			//Console.WriteLine("ReceiveGreeting.In_Connection");
			try
			{
				var msg = new byte[greetingBytes.Length];
				conn.Reader.Read(msg); //NetworkStreamExtensions.ReadExactly(conn.InputStream, greetingBytes.Length);
                if (ByteExtensions.ArrayEquals(msg, greetingBytes))
					Out_ValidConnection(conn);
				else
					Out_InvalidConnection(conn.Client);
			}
			catch
			{
				Out_InvalidConnection(conn.Client);
			}
		}

		public event ValidConnectionHandler Out_ValidConnection;

        public event TcpClientHandler Out_InvalidConnection;

		public void Inject(SecuritySettings securitySettings)
		{
			greetingBytes = Encoding.UTF8.GetBytes(securitySettings.Greeting);
			//maxWaitForGreetingSeconds = securitySettings.SecondsAfterInvalidConnectionIsClosed;
		}
	}
}